package com.infore.airsupervise.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.CompareAnalyzeAdapter;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.CompareE;
import com.infore.airsupervise.biz.StatisticsBiz;
import com.infore.airsupervise.biz.impl.StatisticsBizImpl;
import com.infore.airsupervise.http.HttpUtil;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.StationTreeFragment;
import com.infore.airsupervise.ui.widget.EmptyView;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.FileUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * 统计模块 同比环比 界面
 * Created by xiaotao on 2017/8/17.
 */

public class CompareAnalyzeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.segment_map)
    SegmentedGroup segmentCompare;
    @BindView(R.id.tv_time)
    EditText tvTime;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.emptyView)
    EmptyView emptyView;

    //同比环比
    private int compareType = 0;
    //时间
    private TimePickerView timePickerView = null;
    private String time; //
    private String beforeTime;
    private boolean[] timeType = {true, true, false, false, false, false};

    //站点数树
    private StationTreeFragment drawFragment = null;
    //网络请求

    private StatisticsBiz statisticsBiz = null;
    private String listMN = "";

    //适配器
    private CompareAnalyzeAdapter adapter = null;
    private List<CompareE> data;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compare_analyze);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        segmentCompare.setOnCheckedChangeListener(checkChangeListener);
        //时间
        Calendar curCalendar = Calendar.getInstance();
        curCalendar.add(Calendar.MONTH, -1);
        time = DateUtil.getStringByFormat(curCalendar.getTime(), DateUtil.dateFormatYM);
        tvTime.setText(time);
        //刷新控件
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Color.rgb(52, 152, 219), Color.rgb(231, 76, 60), Color.rgb(46, 204, 113));
        //recyclerView
        data = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
        adapter = new CompareAnalyzeAdapter(data);
        recyclerView.setAdapter(adapter);
        // 提示选择站点
      //  ToastUtil.showLong(this, "请选择站点进行分析");
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                onRefresh();
            }
        });
    }

    /**
     * 时间选择器
     */
    private void initTimePicker() {
        Calendar endSelectedDate = Calendar.getInstance();
        endSelectedDate.add(Calendar.MONTH, -1);
        timePickerView = new TimePickerView.Builder(ctx, timeSelectListener)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(timeType)
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null, endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .setTitleText("时间选择")
                .build();
    }



    /**
     * 站点树fragment
     */
    private void initStationTreeFragment() {
        if (drawFragment == null) {
            drawFragment = new StationTreeFragment();
            drawFragment.setCurType(StationExpandAdapter.CB_SELECTE);
            drawFragment.setOnClickListener(onClicklistener);
            getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawFragment).commit();
        }
    }

    /**
     * 控制抽屉开关
     */
    private void drawerLayout() {
        if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        } else {
            drawerLayout.closeDrawers();
        }
    }

    private void setTime() {
        Calendar befCalendar = Calendar.getInstance();
        befCalendar.setTime(DateUtil.stringToDate(time, DateUtil.dateFormatYM));
        if (compareType == 0) {
            befCalendar.add(Calendar.YEAR, -1);
        } else if (compareType == 1) {
            befCalendar.add(Calendar.MONTH, -1);
        }
        beforeTime = DateUtil.getStringByFormat(befCalendar.getTime(), DateUtil.dateFormatYM);
    }

    /**
     * 加减一段时间
     * @param offset
     * @return
     */
    private boolean timeOffset(int offset){
        boolean isEnd = DateUtil.compareDate(time,
                DateUtil.getStringByOffset(Calendar.getInstance().getTime(),DateUtil.dateFormatYM,Calendar.MONTH,-1),
                DateUtil.dateFormatYM) <= 0;
        if(!isEnd ||(offset < 0) ){
            time = DateUtil.getStringByOffset(time,DateUtil.dateFormatYM,Calendar.MONTH,offset);
            tvTime.setText(time);
        }
        return  isEnd;
    }

    /**
     * 网络请求
     */
    private void getCompareData() {
        if (statisticsBiz == null) {
            statisticsBiz = new StatisticsBizImpl();
        }
        if (listMN == null) {
            ToastUtil.showShort(ctx, "请先选择站点");
            refreshLayout.setRefreshing(false);
            return;
        }
        if (time == null) {
            ToastUtil.showShort(ctx, "请先选择时间");
            refreshLayout.setRefreshing(false);
            return;
        }
        statisticsBiz.sendConstractRequest(time, listMN, compareType, onResponseListener);
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.titlebar_left_menu, R.id.sel_station, R.id.iv_before, R.id.tv_time, R.id.iv_after ,R.id.emptyView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_left_menu:
                finish();
                break;
            case R.id.sel_station:
                initStationTreeFragment();
                drawerLayout();
                break;
            case R.id.iv_before:
                timeOffset(-1);
                getCompareData();
                break;
            case R.id.tv_time:
                if (timePickerView == null) {
                    initTimePicker();
                }
                timePickerView.show();
                break;
            case R.id.iv_after:
                if(timeOffset(1)){
                    ToastUtil.showShort(ctx,"不能超过当前日期");
                }else {
                    getCompareData();
                }
                break;
            case R.id.emptyView :
                emptyView.setVisibility(View.GONE);
                refreshLayout.setRefreshing(true);
                getCompareData();
                break;
        }
    }

    /**
     * 同比 环比切换
     */
    private RadioGroup.OnCheckedChangeListener checkChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            if (checkedId == R.id.rb_TB) { //同比
                compareType = 0;
            } else if (checkedId == R.id.rb_HB) { //环比
                compareType = 1;
            }
            if (listMN != null) {
                refreshLayout.setRefreshing(true);
                getCompareData();
            }
        }
    };


    /**
     * 时间选择回调
     */
    private TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            time = DateUtil.getStringByFormat(date, DateUtil.dateFormatYM);
            tvTime.setText(time); //设置时间xianshiUI
            refreshLayout.setRefreshing(true);
            getCompareData();
        }
    };

    /**
     * 站点树点击事件
     */
    private StationTreeFragment.OnClickListener onClicklistener = new StationTreeFragment.OnClickListener() {
        @Override
        public void onConfirmClick(String mn) {
            drawerLayout();
            listMN = mn;
            refreshLayout.setRefreshing(true);
            getCompareData();

        }

        @Override
        public void onConfirmClick(String mn, String name) {

        }

        @Override
        public void onCancelClick() {
            drawerLayout();
        }
    };

    /**
     * 刷新布局 回调
     */
    @Override
    public void onRefresh() {
        getCompareData();
    }

    private OnServerResponseListener<List<CompareE>> onResponseListener = new OnServerResponseListener<List<CompareE>>() {
        @Override
        public void onSucceed(List<CompareE> result, String desc) {
            refreshLayout.setRefreshing(false);
            if (result == null) {
                return;
            }
            if(result.size()<= 0 ){
                emptyView.setShowInfo(R.drawable.status_search_null, MsgConst.EMPTY_DATA);
                emptyView.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            }else {
                emptyView.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
            }
            data.clear();
            data.addAll(result);
            setTime(); //根据参照时间设置对比时间
            adapter.setLabelTime(time, beforeTime);
            adapter.setCompareType(compareType);
            adapter.notifyDataSetChanged();
            recyclerView.scrollToPosition(0);
        }

        @Override
        public void onFailed(int errorCode, String title, String desc) {
          //  ToastUtil.showShort(ctx, title + "\n" + desc);
            refreshLayout.setRefreshing(false);
            emptyView.setShowInfo(HttpUtil.getEmptyRes(errorCode),title);
            emptyView.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }
    };

}
